'use strict'

import axios from 'axios'
import qs from 'qs'

axios.interceptors.request.use(config => {
  return config // loading
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function checkStatus (response, success, failure) {
  // loading
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    if (response.data && response.data.code && (response.data.code === 0 || response.data.code === '0')) {
      // return response
      // 如果不需要除了data之外的数据，可以直接 return response.data
      success && success(response.data.data)
    } else {
      failure && failure({code: response.data.code, message: response.data.message})
    }
  } else {
    // 异常状态下，把错误信息返回去
    failure && failure({code: 400, message: '请求数据发生异常'})
  }
}

function checkCode (res, failure) {
  failure && failure({code: 400, message: '请求数据发生异常'})
}

export default {
  post (url, data, success, failure) {
    return axios({
      method: 'post',
      url,
      baseURL: '/fita-api',
      data: qs.stringify(data),
      timeout: 30000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        let result = typeof response === 'object' ? response : JSON.parse(response)
        return checkStatus(result, success, failure)
      }
    ).catch(
      (error) => {
        return checkCode(error, failure)
      }
    )
  },
  get (url, params, success, failure) {
    return axios({
      method: 'get',
      baseURL: '/fita-api',
      url,
      params, // get 请求时带的参数
      timeout: 30000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response, success, failure)
      }
    ).catch(
      (error) => {
        return checkCode(error, failure)
      }
    )
  }
}
